package world;

import java.util.ArrayList;
import java.util.Vector;

import control.GUI.Output;

public class MainSimulator extends Thread {

	private Vector<String> queries;
	public volatile boolean stop, finished;
	private World w;
	private Output out;

	public MainSimulator(Output out) {
		queries = new Vector<String>();
		stop = false;
		finished = true;
		this.out = out;

		// File wF = new File(worldFile);
		// if (wF.exists()) {
		// try {
		// Object o = ObjectIO.readFromFile(worldFile);
		// w = (World) o;
		// } catch (Exception e) {
		// System.err.println("Could not read world file, backing up...");
		// e.printStackTrace();
		// File target = new File("worldFileBackup_"
		// + Timestamp.getTimestamp(true) + ".dat");
		// if (wF.renameTo(target)) {
		// System.err.println("Backup successful");
		// } else {
		// System.err.println("Backup NOT successful");
		// }
		// System.err.println("Generating new world");
		// w = new World();
		// }
		// } else {
		w = new World();
		// }
	}

	@Override
	public void run() {
		while (!stop) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}

			while (!finished) {
				String query = queries.remove(0);
				if (query.equals("")) {
					w.tick(out);
				}
				if (query.startsWith("wait ")) {
					query = query.replaceAll("wait", "").trim();
					try {
						int reps = Integer.parseInt(query);
						for (int c0 = 0; c0 < reps; c0++) {
							w.tick(out);
						}
					} catch (NumberFormatException e) {
						out.push("Error: Could not interpret the number \""
								+ query + "\"");
					}

				}

				w.report(out);

				finished = true;
			}

		}

		// try {
		// ObjectIO.writeToFile(w, worldFile);
		// } catch (FileNotFoundException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
	}

	public void addQuery(String q) {
		queries.add(q);
		this.interrupt();
	}

	/**
	 * @return All visible physical objects in the game world
	 */
	public ArrayList<PhysicalObject> getVisibleObjects() {
		return w.getVisibleObjects();
	}

	public utility.Vector getWorldSize() {
		return w.getSize();
	}
}
